// pages/operation/class/classSchedule/index.js、
import formRules from "../../../../utils/rules-form.js"
import {
  LessonModel
} from "../../../../api/api-work/lesson.js";
import {
  ClassModel
} from "../../../../api/api-work/classModel.js"
import {
  timestampToTime
} from "../../../../utils/index.js"
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
const lessonModel = new LessonModel()
const classModel = new ClassModel()
const rules = {
  courseName: [{
    required: true,
    message: '请选择授课课程'
  }],
  className: [{
    required: true,
    message: '请选择班级'
  }],
  teacherName: [{
    required: true,
    message: '请选择主任老师'
  }],
  classHour: [{
    required: true,
    message: '请输入授课课时'
  }],
  startDate: [{
    required: true,
    message: '请选择开始日期'
  }],
  endDate: [{
    required: true,
    message: '请选择结束日期'
  }],
  classStartTime: [{
    required: true,
    message: '请选择上课时间'
  }],
  classEndTime: [{
    required: true,
    message: '请选择下课时间'
  }],
}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 传值
    id: "", // 排课信息的id
    idsStr: "",
    lessonType: "",
    className: "", // 班级
    classId: "", // 班级id

    courseId: "", // 课程id
    courseName: "请选择", // 课程名称（显示用）
    coursePickers: [], // 课程列表
    showCourse: false, // 课程显示

    teacherName: "请选择",
    teacher: "",
    showTeacher: false, // 主班老师显示
    teacherList: [], // 主班老师列表

    showAssistant: false,
    assistantArr: [], // 助教
    assistantName: "请选择", // 助教老师拼接显示
    assistant: "", // 助教老师拼接id

    classRoom: "",
    showRoom: false, // 上课教室
    classRoomName: "请选择",
    roomList: [], // 教室列表

    classHour: "", // 授课课时
    showStartDate: false, // 开始日期
    startDate: "请选择", // 显示传值
    currentStartDate: new Date().getTime(),
    minDate: new Date(2020, 0, 1).getTime(),

    showEndDate: false, // 结束日期
    endDate: "请选择", // 显示传值
    currentEndDate: new Date().getTime(),

    circulateType: "1", // 重复方式 1：每天重复 2：每周重复
    classStartTime: "", // 上课时间
    // 上课时间
    showStartTime: false,
    filterStartTime(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 5 === 0);
      }
      return options;
    },
    classEndTime: "", // 下课时间
    // 下课时间
    showEndTime: false,
    filterEndTime(type, options) {
      if (type === 'minute') {
        return options.filter((option) => option % 5 === 0);
      }
      return options;
    },
    showWeek: false, // 星期
    weekName: "请选择", // 显示
    weekNum: "", // 传值
    weekColumns: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    description: "", // 上课内容
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const params = JSON.parse(options.params);
    if (params.id == undefined || params.id == "") {
      wx.setNavigationBarTitle({
        title: '新建排课',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '编辑排课',
      })
    }
    this.setData({
      idsStr: params.idsStr,
      lessonType: params.lessonType,
      className: params.className,
      classId: params.classId,
      id: params.id
    })
    if (params.id == undefined || params.id == "") {
      // 一键排课
    } else {
      // 获取排课信息
      await this.getCourseOrderConfigById()
    }

    // 获取课程
    await this.getLesson();
    // 获取主班老师
    await this.getTeacherList();
    // 获取助教老师
    await this.getAssistantList();
    // 获取上课教室
    await this.getClassRoomList();

  },

  // 根据id 获取排课信息
  async getCourseOrderConfigById() {
    classModel.getCourseOrderConfigByIdApi({
      id: this.data.id
    }).then(res => {

      this.setData({
        courseId: res.courseId,
        teacher: res.teacher,
        assistant: res.assistant,
        assistantArr: res.assistantArr,
        classRoom: res.classRoom,
        classHour: res.classHour,
        startDate: res.startTime.split(" ")[0],
        currentStartDate: new Date(timestampToTime(res.startTime.split(" ")[0])).getTime(),
        endDate: res.endTime.split(" ")[0],
        currentEndDate: new Date(timestampToTime(res.endTime.split(" ")[0])).getTime(),
        circulateType: res.circulateType.toString(),
        classStartTime: res.classStartTime,
        classEndTime: res.classEndTime,
        weekNum: res.weekNum,
        weekName:res.weekNum ? this.data.weekColumns[res.weekNum-1]:'请选择',
        description: res.description
      })
    })
  },

  // 获取课程
  async getLesson() {
    lessonModel.getLessonApi({
      pageNum: 1,
      pageSize: 999,
      state: "0",
      idsStr: this.data.idsStr,
      lessonType: this.data.lessonType
    }).then(res => {
      if (res.rows.length > 0) {
        res.rows.forEach(item => {
          if (item.id == this.data.courseId) {
            item['isChecked'] = true;
            this.setData({
              courseName: item.name
            })
          } else {
            item['isChecked'] = false;
          }
        })
      }
      this.setData({
        coursePickers: res.rows
      })
    })
  },
  showCoursePopup() {
    this.setData({
      showCourse: true
    })
  },
  onCloseCourse() {
    this.setData({
      showCourse: false
    })
  },
  onCheckCourse(e) {
    this.data.coursePickers.forEach(item => {
      if (item.id == e.currentTarget.dataset.query.id) {
        item.isChecked = true;
      } else {
        item.isChecked = false;
      }
    })
    this.setData({
      coursePickers: this.data.coursePickers
    })
  },
  chooseCourse() {
    this.data.coursePickers.forEach(item => {
      if (item.isChecked) {
        this.setData({
          showCourse: false,
          courseName: item.name,
          courseId: item.id
        })
      }
    })
  },

  // 获取主班老师列表
  async getTeacherList() {
    classModel.getStaffPeopleListApi().then(res => {
      console.log("sss: ", res)
      if (res.length > 0) {
        res.forEach(item => {
          if (item.value == this.data.teacher) {
            item['isChecked'] = true;
            this.setData({
              teacherName: item.label
            })
          } else {
            item['isChecked'] = false;
          }
        })
      }
      this.setData({
        teacherList: res.filter(item => item.isJob == true),
      })
    })
  },
  // 主班老师
  showTeacherPopup() {
    this.setData({
      showTeacher: true
    })
  },
  onCloseTeacher() {
    this.setData({
      showTeacher: false
    })
  },
  // 选择主班老师  单选
  onCheckTeacher(e) {
    this.data.teacherList.forEach(item => {
      if (item.value == e.currentTarget.dataset.query.value) {
        item.isChecked = true
      } else {
        item.isChecked = false
      }
    })
    this.setData({
      teacherList: this.data.teacherList
    })
  },
  chooseTeacher() {
    this.data.teacherList.forEach(item => {
      if (item.isChecked) {
        this.setData({
          showTeacher: false,
          teacherName: item.label,
          teacher: item.value
        })
      }
    })
  },

  // 助教老师列表
  async getAssistantList() {

    classModel.getStaffPeopleListApi().then(res => {
      if (res.length > 0) {
        let arrName = []
        res.forEach(item => {
          if (this.data.assistantArr && this.data.assistantArr.indexOf(item.value) != -1) {
            item['isChecked'] = true;
            arrName.push(item.label);
            this.setData({
              assistantName: arrName.join(",")
            })
          } else {
            item['isChecked'] = false;
          }
        })
      }
      this.setData({
        assistantList: res.filter(item => item.isJob == true),
      })
    })
  },
  showAssistantPopup() {
    this.setData({
      showAssistant: true
    })
  },
  onCloseAssistant() {
    this.setData({
      showAssistant: false
    })
  },
  onCheckAssistant(e) {
    this.data.assistantList.forEach(item => {
      if (item.value == e.currentTarget.dataset.query.value) {
        item.isChecked = !item.isChecked
      }
    })
    this.setData({
      assistantList: this.data.assistantList
    })
  },
  chooseAssistant() {
    let arrIds = [];
    let arrLabels = [];
    this.data.assistantList.forEach(item => {
      if (item.isChecked) {
        arrIds.push(item.value);
        arrLabels.push(item.label)
      }
    })
    this.setData({
      showAssistant: false,
      assistantName: arrLabels.join(","),
      assistant: arrIds.join(","),
      assistantArr: arrIds
    })
  },

  // 上课教室列表
  async getClassRoomList() {
    classModel.getClassRoomListApi({
      lableType: "class_room"
    }).then(res => {
      if (res.length > 0) {
        res.forEach(item => {
          if (item.id == this.data.classRoom) {
            item['isChecked'] = true;
            this.setData({
              classRoomName: item.name
            })
          } else {
            item['isChecked'] = false
          }
        })
      }
      this.setData({
        roomList: res
      })
    })
  },
  showRoomPopup() {
    this.setData({
      showRoom: true
    })
  },
  onCloseRoom() {
    this.setData({
      showRoom: false
    })
  },
  onCheckRoom(e) {
    this.data.roomList.forEach(item => {
      if (item.id == e.currentTarget.dataset.query.id) {
        item.isChecked = true
      } else {
        item.isChecked = false
      }
    })
    this.setData({
      roomList: this.data.roomList
    })
  },
  chooseRoom() {
    this.data.roomList.forEach(item => {
      if (item.isChecked) {
        this.setData({
          showRoom: false,
          classRoom: item.id,
          classRoomName: item.name
        })
      }
    })
  },

  // 授课课时
  onStepChange(e) {
    this.setData({
      classHour: e.detail
    })
  },

  // 开始日期
  showStartDatePopup() {
    this.setData({
      showStartDate: true,
    })
  },
  onCloseStartDate() {
    this.setData({
      showStartDate: false
    })
  },
  chooseStartDate(e) {
    if (this.data.endDate != "请选择") {
      if (new Date(timestampToTime(e.detail)).getTime() > new Date(this.data.endDate).getTime()) {
        Toast('开始日期不能大于结束日期');
        return;
      }
    }
    this.setData({
      startDate: timestampToTime(e.detail),
      currentStartDate: new Date(timestampToTime(e.detail)).getTime(),
      showStartDate: false
    })
  },

  // 结束日期
  showEndDatePopup() {
    this.setData({
      showEndDate: true
    })
  },
  onCloseEndDate() {
    this.setData({
      showEndDate: false
    })
  },
  chooseEndDate(e) {
    if (this.data.startDate != "请选择") {
      if (new Date(this.data.startDate).getTime() > new Date(timestampToTime(e.detail)).getTime()) {
        Toast('结束日期不能小于开始日期');
        return;
      }
    }
    this.setData({
      endDate: timestampToTime(e.detail),
      currentEndDate: new Date(timestampToTime(e.detail)).getTime(),
      showEndDate: false
    })
  },

  // 重复方式
  onRadioChange(e) {
    console.log("rr: ", e)
    this.setData({
      circulateType: e.detail,
      weekNum:null,
      weekName:'请选择'
    })
  },

  // 上课时间
  showStartTimePopup() {
    this.setData({
      showStartTime: true
    })
  },
  // 选择上课时间
  chooseStartTime(e) {
    const date = new Date();
    const start_time = e.detail.split(":");
    const end_time = this.data.classEndTime.split(":");
    if (date.setHours(start_time[0], start_time[1]) > date.setHours(end_time[0], end_time[1])) {
      Toast('上课时间不能大于下课时间');
      return;
    }
    this.setData({
      showStartTime: false,
      classStartTime: e.detail
    })
  },
  onCloseStartTime() {
    this.setData({
      showStartTime: false
    })
  },

  // 下课时间
  showEndTimePopup() {
    this.setData({
      showEndTime: true
    })
  },
  // 选择下课时间
  chooseEndTime(e) {
    const date = new Date();
    const start_time = this.data.classStartTime.split(":");
    const end_time = e.detail.split(":");
    if (date.setHours(start_time[0], start_time[1]) > date.setHours(end_time[0], end_time[1])) {
      Toast('下课时间不能小于上课时间');
      return;
    }
    this.setData({
      showEndTime: false,
      classEndTime: e.detail
    })
  },
  onCloseEndTime() {
    this.setData({
      showEndTime: false
    })
  },

  showWeekPopup() {
    this.setData({
      showWeek: true
    })
  },
  onCancelWeek() {
    this.setData({
      showWeek: false
    })
  },
  onConfirmWeek(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      showWeek: false,
      weekNum: index + 1,
      weekName: value
    })
  },

  confirmSchedule() {
    const params = {
      id: this.data.id,
      courseId: this.data.courseId, // 授课课程
      classId: this.data.classId, // 班级id
      teacher: this.data.teacher, // 主班老师id
      assistant: this.data.assistant, // 助教老师ids
      classRoom: this.data.classRoom, // 上课教室id
      classHour: this.data.classHour, // 授课课时
      startTime: this.data.startDate, // 开始日期
      endTime: this.data.endDate, // 结束日期
      circulateType: this.data.circulateType, // 重复方式
      classStartTime: this.data.classStartTime, // 上课时间
      classEndTime: this.data.classEndTime, // 下课时间
      weekNum: this.data.weekNum, // 星期
      description: this.data.description, // 上课内容
      type: "1",
    }
    console.log("params: ", params)
    formRules(rules, this.data, (status) => {
      if (status) {
        if (this.data.id == undefined || this.data.id == "") {
          // 新增保存
          classModel.courseOrderSaveApi(params).then(res => {
            wx.navigateBack()
          })
        } else {
          classModel.courseOrderUpdateApi(params).then(res => {
            wx.navigateBack()
          })
        }
      }
    })

  },

  // 删除排课
  deleteSchedule() {
    Dialog.confirm({
      title: "确认删除？"
    }).then(() => {
      classModel.courseOrderDeleteApi({
        id: this.data.id
      }).then(res => {
        wx.navigateBack()
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})